/* 
登陆相关的路由器
*/
const express = require('express')
const { RES_CODE } = require('../utils/contants')
const verifyToken = require('../middlewares/verifyToken')
const { createToken } = require('../utils/tokenUtils')

const router = express.Router()
const md5 = require('md5')
const UserModel = require('../db/models/UserModel')

// 登陆
router.post('/login', async (req, res) => {
  const {username, pwd} = req.body
  try {
    let user = await UserModel.findOne({username, pwd: md5(pwd)})
    console.log('user', user)
    if (user) {
      const token = createToken(user._id)
      res.json({
        code: RES_CODE.SUCCESS,
        data: {
          token,
          user
        }
      })
    } else {
      res.send({
        code: RES_CODE.DATA_ERROR,
        message: '登陆失败, 用户名或密码不正确'
      })
    }
  } catch (error) {
    res.send({
      code: RES_CODE.SERVER_ERROR,
      message: '登陆失败, 服务器端异常'
    })
  }
})

// 获取用户
router.get('/info', verifyToken, async (req, res) => {
  const userId = req.userId

  const user = await UserModel.findById(userId)
  res.send({
    code: RES_CODE.SUCCESS,
    data: user
  })
})

// 登出
router.get('/logout', verifyToken, (req, res) => {
  // 清除后台登陆用户相关的数据

  // 返回成功
  res.send({
    code: RES_CODE.SUCCESS,
    message: '退出登陆成功'
  })
})

module.exports = router